#! /usr/local/bin/perl5
# $Id$
use strict;
use warnings ( FATAL => 'all' );

use lib "../perllib";    #TODO, remove for develop

use Data::Dumper;
use File::Basename;
use Readonly;
use POSIX qw(strftime);

use FixInc::Logger;
use FixInc::DBAccess;
use FixInc::OopOptsDB;
use Feeds::API::File;

use Feeds::Utils::CDSBrokerFeedMeta;
use Feeds::GCF::DbLock;

use constant SCRIPT_NM => basename($0);
use constant LOCK_TP   => 'P_NORM';
use constant LOCK_USER => 'autosys';

Readonly my $HOST_NM => $ENV{HOST} || `hostname | tr -d '\n'`;
Readonly my $NOW => strftime( '%Y%m%d.%H%M%S', localtime );
Readonly my $TODAY => $ENV{TODAY_CYMD} || substr( $NOW, 0, 8 );

# Turn on output autoflush
$| = 1;

my $l = FixInc::Logger->new( min_level => 'notice' );
my $script_nm = SCRIPT_NM;
$l->notice("=== $script_nm has started === (pid=$$) (ppid=@{[getppid()]})");
$l->info( "CMD:", $0, join( " ", @ARGV ) );

## Parse Jobparams ##
my $defs = FixInc::OopOptsDB->newOptSet(
    help => <<'EOH',
This script updates the normalized tables from the vendor tables with the most recent data.
EOH

    defaults => { sql_changeset_mode => 'tran',
    	           
    	          },
    optdefs  => FixInc::OopOptsDB->newOptDef(
        {   name    => 'candidate_status',
            aliases => [],
            maxargs => 1,
            type    => 'string',
            help    => 'status for transform.'
        },
        {   name    => 'load_limit',
            aliases => [],
            maxargs => 1,
            type    => 'int',
            help    => 'how many CDS can load one time'
        },
        {   name    => 'exc_plugin',
            aliases => [],
            maxargs => 1,
            type    => 'string',
            help    => 'plugin for exception'
        },
        {   name    => 'map_plugin',
            aliases => [],
            maxargs => 1,
            type    => 'string',
            help    => 'plugin for mapping'
        },
        {   name    => 'candidate_list',
            aliases => ['cl'],
            maxargs => 30,
            type    => 'string',
            help    => 'list of candidate of oid in ntbl'
        },
        {   name    => 'sql_changeset_mode',
            aliases => [],
            maxargs => 1,
            type    => 'string',
            help    => 'default is tran'
        },
        {   name    => 'exc_recheck_fl',
            aliases => [],
            maxargs => 1,
            type    => 'string',
            help    => 'there are three recheck level, A,B,C, the larger the chracter, 
                        means check exception more offen, if set recheck_fl=B, then both
                        B and C exception will be checked, default is B
                        B is applied to daily run, C applied to intra-day run'
        },
        
         {  name    => 'exclude',
            aliases => [],
            maxargs => 3,
            type    => 'string',
            help    => 'exclude sn(singlename), idx(index) or tranche'
        },
        
        

    )
);

my $log = FixInc::Logger->new( min_level => 'info' );

my $oops = FixInc::OopOptsDB->new(
    'optset' => $defs,
    'log'    => $log
    )
    or $l->die("Cannot process options: FixInc::OopOptsDB->new");

my $O = $oops->opthash;
$log->paramApply($O);

## Connect to the Feed DB ##
my $feed_dbh = Feeds::API::FeedDB->paramApply($O)->connect( %$O, log => $log )
    or $log->die("Attempting database connection: Feeds::API::Job->connect");

## Fetch the feed meta data ##
my $fmeta = Feeds::Utils::CDSBrokerFeedMeta->new(
    log       => $log,
    dbh       => $feed_dbh,
    feed_type => $O->{feed_type}
    )
    or $log->die("Cannot get feed meta data for $O->{feed_type}");

## Require a plugin to do the exception ##
my $exc_class = ( $O->{exc_plugin} =~ /::/ ? "" : 'Feeds::Transform::' )
    . $O->{exc_plugin};

eval "require $exc_class";
$log->die("Unable to require class '$exc_class': $@") if $@;

## Require a plugin to do the Map ##
my $map_class = ( $O->{map_plugin} =~ /::/ ? "" : 'Feeds::Transform::' )
    . $O->{map_plugin};

eval "require $map_class";
$log->die("Unable to require class '$map_class': $@") if $@;

$log->info("start check exception");

# Instantiate a Exception::plugin
my $exc_obj = $exc_class->new(
    log   => $log,
    dbh   => $feed_dbh,
    fmeta => $fmeta,
    param => $O
);

my ( $sn_candidates, $idx_candidates, $tranche_candidates,$volume_candidates ) = $exc_obj->run();

$log->info("end check exception");
$log->info( "sn_candidates num:" . scalar @$sn_candidates )
    if ($sn_candidates);
$log->info( "idx_candidates num:" . scalar @$idx_candidates )
    if ($idx_candidates);
$log->info( "tranche_candidates num:" . scalar @$tranche_candidates )
    if ($tranche_candidates);
    
$log->info( "volume_candidates num:" . scalar @$volume_candidates )
    if ($volume_candidates);

#$log->info("start mapping and generate sql");
#
#my $map_obj = $map_class->new(
#    log          => $log,
#    dbh          => $feed_dbh,
#    fmeta        => $fmeta,
#    param        => $O,
#    index_data   => $idx_candidates,
#    sn_data      => $sn_candidates,
#    tranche_data => $tranche_candidates,
#    volume_data  => $volume_candidates,
#);
#
#$map_obj->run();

$feed_dbh->disconnect() if defined $feed_dbh;

$log->notice("=== @{[SCRIPT_NM]} has stopped ===");

